package cshi.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Car {
	private boolean waxOn = false;
	public synchronized void waxed(){
		waxOn = true;
		notifyAll();//ready to buff(准备给车子抛光)
	}
	
	public synchronized void buffed(){
		waxOn = false;
		notifyAll();
	}
	
	public synchronized void waitForWaxing() throws InterruptedException{
		while (waxOn == false) //写成了=，结果输出很奇怪
			wait();
	}
	
	public synchronized void waitForBuffing() throws InterruptedException{
		while (waxOn == true)//写成了=，结果输出很奇怪
			wait();
	}
}

class WaxOn implements Runnable{
	private Car car;
	public WaxOn(Car c) {
		// TODO Auto-generated constructor stub
		car = c;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			while (!Thread.interrupted()){
				System.out.println("wax on");
				TimeUnit.MILLISECONDS.sleep(200);//模拟上蜡的时间
				car.waxed();
				car.waitForBuffing();//上蜡之后等待抛光
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("waxon interrupt");
		}
	}
	
}

class WaxOff implements Runnable{
	private Car car;
	public WaxOff(Car c) {
		// TODO Auto-generated constructor stub
		car = c;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			while (!Thread.interrupted()){
				car.waitForWaxing();//等待上蜡
				System.out.println("wax off");
				TimeUnit.MILLISECONDS.sleep(200);
				car.buffed();//上蜡成功后就抛光
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("waxoff interrupt");
		}
	}
	
}
public class WaitAndNotify {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		Car car = new Car();
		ExecutorService es = Executors.newCachedThreadPool();
		es.execute(new WaxOff(car));
		es.execute(new WaxOn(car));
		TimeUnit.SECONDS.sleep(5);
		es.shutdownNow();//interrupt all tasks
	}

}
